package com.artup.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.AddressDao;
import com.artup.pojo.Address;
import com.artup.pojo.Region;
import com.artup.service.AddressService;
import com.artup.util.CommonUtils;
import com.artup.util.cache.RedisUtils;

import redis.clients.jedis.Jedis;

@Service( value = "addressService" )
public class AddressServiceImpl implements AddressService {
	protected static final Logger LOGGER = LoggerFactory.getLogger(AddressServiceImpl.class);

	@Autowired
	private AddressDao addressDao;
	
	private static Jedis jedis = RedisUtils.getJedis();
	
	@Override
	public ResponseResult saveAddress(Address address) {
		LOGGER.info("address = {}", JSONObject.toJSONString(address));
		
		ResponseResult responseResult = new ResponseResult();
		 
		if(null == address) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		} else if(null == address.getPassportId()) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【通行证ID】不可为空！");
			
			return responseResult;
		} else if(0 >= address.getPassportId()) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【通行证ID】只能为正整数！");
			
			return responseResult;
		}
		
		if("Y".equalsIgnoreCase(address.getIsDefault())){
			try {
				this.addressDao.updateAddressNotDefaultByPassportId(address.getPassportId());
			} catch (SQLException e) {
				LOGGER.error("根据【通行证ID】更新当前会员名下的【地址】为非默认 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("根据【通行证ID】更新当前会员名下的【地址】为非默认 - 失败！");
				
				return responseResult;
			}
		}
		
		address.setId(CommonUtils.UUIDGenerator());
		
		try {
			this.addressDao.insertAddress(address);
		} catch (Exception e) {
			LOGGER.error("添加地址 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("添加地址 - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("添加地址 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult updateAddressById(Address address) {
		LOGGER.info("address = {}", JSONObject.toJSONString(address));
		
		ResponseResult responseResult = new ResponseResult();
		 
		if(null == address) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("无参数！");
			
			return responseResult;
		} else if(StringUtils.isBlank(address.getId())) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("ID 不可为空！");
			
			return responseResult;
		}
		
		if("y".equalsIgnoreCase(address.getIsDefault())) {
			try {
				this.addressDao.updateAddressNotDefaultById(address.getId());
			} catch (SQLException e) {
				LOGGER.error("根据【ID】更新当前会员名下的【地址】为非默认 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("根据【ID】更新当前会员名下的【地址】为非默认 - 失败！");
				
				return responseResult;
			}
		}
		
		try {
			this.addressDao.updateAddressById(address);
		} catch (Exception e) {
			LOGGER.error("根据【ID】更新【地址】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】更新【地址】 - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("更新地址 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult deleteAddressById(String id) {
		LOGGER.info("id = {}", id);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(StringUtils.isBlank(id)) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("ID 不可为空！");
			
			return responseResult;
		}
		
		try {
			this.addressDao.deleteAddressById(id);
		} catch (Exception e) {
			LOGGER.error("根据【ID】删除【地址】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】删除【地址】 - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("删除地址 - 成功。");
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryDefaultAddressByPassportId(int passportId) {
		LOGGER.info("passportId = {}", passportId);
		
		ResponseResult responseResult = new ResponseResult();
		 
		if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("【通行证ID】必须为正数！");
			
			return responseResult;
		}
		
		Address address = null;
		try {
			address = this.addressDao.selectDefaultAddressByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询默认【地址】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询默认【地址】 - 失败！");
			
			return responseResult;
		}
		
		Map<String, Object> addressMap = new HashMap<String, Object>();
		if(null != address) {
			addressMap.put("id", address.getId());
			addressMap.put("name", address.getName());
			addressMap.put("mobileCode", address.getMobileCode());
			
//			jedis = RedisUtils.getJedis();
//			List<String> regionList = jedis.lrange(Constants.CACHE_TYPE_REGION_LIST, 0, -1);
			String regions = jedis.get(Constants.CACHE_TYPE_REGION_LIST);
			
			/*String regions = null;
			List<String> regionList_ = jedis.mget(Constants.CACHE_TYPE_REGION_LIST);
			if(null != regionList_) {
				regions = regionList_.get(0);
			}*/
			
			if(CommonUtils.isNotEmpty(regions)) {
				StringBuilder detail = new StringBuilder();
				List<Region> regionList = JSONArray.parseArray(regions, Region.class);
				for(Region region : regionList) {
					if(address.getProvinceId() == region.getId()){
						detail.append(region.getName());
					}
				}
				for(Region region : regionList) {
					if(address.getCityId() == region.getId()){
						detail.append(region.getName());
					}
				}
				for(Region region : regionList) {
					if(address.getDistrictId() == region.getId()){
						detail.append(region.getName());
					}
				}
				
				detail.append(address.getDetail());
				addressMap.put("detail", detail);
			}
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询默认【地址】 - 成功。");
		responseResult.setData(addressMap);
		
		return responseResult;
	}
	
	@Override
	public ResponseResult queryAddressListByPassportId(int passportId) {
		LOGGER.info("passportId = {}", passportId);
		
		ResponseResult responseResult = new ResponseResult();
		 
		if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("【通行证ID】必须为正数！");
			
			return responseResult;
		}
		
		List<Address> addressList = null;
		try {
			addressList = this.addressDao.selectAddressListByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询默认【地址】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询默认【地址】 - 失败！");
			
			return responseResult;
		}

		if(CommonUtils.isNotEmpty(addressList)) {
			List<Map<String, Object>> addressResultList = new ArrayList<Map<String, Object>>();
			
			jedis = RedisUtils.getJedis();
			String regions = jedis.get(Constants.CACHE_TYPE_REGION_LIST);
			
			/*String regions = null;
			List<String> regionList_ = jedis.mget(Constants.CACHE_TYPE_REGION_LIST);
			if(null != regionList_) {
				regions = regionList_.get(0);
			}*/
			
			for(Address address : addressList) {
				if(null == address) {
					continue;
				}
				
				Map<String, Object> addressMap = new HashMap<String, Object>();
				addressMap.put("id", address.getId());
				addressMap.put("name", address.getName());
				addressMap.put("mobileCode", address.getMobileCode());
				addressMap.put("isDefault", address.getIsDefault());
//				addressMap.put("provinceId", address.getProvinceId());
//				addressMap.put("cityId", address.getCityId());
//				addressMap.put("districtId", address.getDistrictId());
//				addressMap.put("detail", address.getDetail());
				
				if(CommonUtils.isNotEmpty(regions)) {
					StringBuilder detail = new StringBuilder();
					List<Region> regionList = JSONArray.parseArray(regions, Region.class);
					for(Region region : regionList) {
						if(address.getProvinceId() == region.getId()){
							detail.append(region.getName());
						}
					}
					for(Region region : regionList) {
						if(address.getCityId() == region.getId()){
							detail.append(region.getName());
						}
					}
					for(Region region : regionList) {
						if(address.getDistrictId() == region.getId()){
							detail.append(region.getName());
						}
					}
					
					detail.append(address.getDetail());
					addressMap.put("detail", detail);
				}

				addressResultList.add(addressMap);
			}

			responseResult.setData(addressResultList);
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【我的地址列表】 - 成功。");
		
		return responseResult;
	}

	@Override
	public ResponseResult queryAddressListByPassportId2(int passportId) {
		LOGGER.info("passportId = {}", passportId);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(0 >= passportId) {
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("【通行证ID】必须为正数！");
			
			return responseResult;
		}
		
		List<Address> addressList = null;
		try {
			addressList = this.addressDao.selectAddressListByPassportId(passportId);
		} catch (Exception e) {
			LOGGER.error("根据【通行证ID】查询默认【地址】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【通行证ID】查询默认【地址】 - 失败！");
			
			return responseResult;
		}
		
		if(CommonUtils.isNotEmpty(addressList)) {
			List<Map<String, Object>> addressResultList = new ArrayList<Map<String, Object>>();
			
			jedis = RedisUtils.getJedis();
			String regions = jedis.get(Constants.CACHE_TYPE_REGION_LIST);
			
			/*String regions = null;
			List<String> regionList_ = jedis.mget(Constants.CACHE_TYPE_REGION_LIST);
			if(null != regionList_) {
				regions = regionList_.get(0);
			}*/
			
			for(Address address : addressList) {
				if(null == address) {
					continue;
				}
				
				Map<String, Object> addressMap = new HashMap<String, Object>();
				addressMap.put("id", address.getId());
				addressMap.put("name", address.getName());
				addressMap.put("mobileCode", address.getMobileCode());
				addressMap.put("isDefault", address.getIsDefault());
				addressMap.put("provinceId", address.getProvinceId());
				addressMap.put("cityId", address.getCityId());
				addressMap.put("districtId", address.getDistrictId());
				addressMap.put("detail", address.getDetail());
				
				if(CommonUtils.isNotEmpty(regions)) {
					List<Region> regionList = JSONArray.parseArray(regions, Region.class);
					for(Region region : regionList) {
						if(address.getProvinceId() == region.getId()){
							addressMap.put("provinceName", region.getName());
						}
						if(address.getCityId() == region.getId()){
							addressMap.put("cityName", region.getName());
						}
						if(address.getDistrictId() == region.getId()){
							addressMap.put("districtName", region.getName());
						}
					}
				}
				
				addressResultList.add(addressMap);
			}
			
			responseResult.setData(addressResultList);
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【我的地址列表】 - 成功。");
		
		return responseResult;
	}
	
	@Override
	public ResponseResult updateAddressDefaultById(String id) {
		LOGGER.info("id = {}", id);
		
		ResponseResult responseResult = new ResponseResult();
		 
		if(StringUtils.isBlank(id)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【ID】不可为空！");
			
			return responseResult;
		}
		
		try {
			this.addressDao.updateAddressNotDefaultById(id);
		} catch (SQLException e) {
			LOGGER.error("根据【ID】更新当前会员名下的【地址】为非默认 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】更新当前会员名下的【地址】为非默认 - 失败！");
			
			return responseResult;
		}
		
		try {
			this.addressDao.updateAddressDefaultById(id);
		} catch (SQLException e) {
			LOGGER.error("根据【ID】更新【地址】为默认 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("根据【ID】更新【地址】为默认 - 失败！");
			
			return responseResult;
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("更新【地址】为默认 - 成功。");
		
		return responseResult;
	}
}
